<template>
  <div class="app-container">
    <!-- 标题区域 -->
    <div class="header">
      <h1>建仓报表</h1>
      <div class="upload-button">
        <el-button type="primary" @click="downloadExcel">
          <i class="el-icon-download"></i> 下载excel表格
        </el-button>
      </div>
    </div>
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-input
          v-model.trim="searchKeyword"
          placeholder="请输入FBA码或产品sku搜索"
          clearable
          style="width: 300px;"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>

      <el-input
          v-model.trim="searchStaffNameKeyword"
          placeholder="请输入员工姓名搜索"
          clearable
          style="width: 300px;"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          :data="currentPageData"
          :key="tableKey"
          stripe
          border
          empty-text="暂无数据，请先添加"
          highlight-current-row
          style="width: 100%"
      >
        <!-- 静态列 -->
        <el-table-column prop="fbaCode" label="FBA码" width="150" sortable />
        <el-table-column prop="sku" label="产品SKU" width="150" sortable />
        <el-table-column v-for="key in dynamicKeys"
                         :prop="key"
                         :label="tableHead.data[key]"
                         width="150"
                         sortable >
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
          background
          layout="sizes, prev, pager, next, jumper, ->, total"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          :total="totalItems"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>
  </div>

</template>

<script>
import {computed,ref,reactive} from "vue";
import {ElMessage} from "element-plus";
import {Search} from "@element-plus/icons-vue";
import generateFormStructure from "@/hooks/common/generateFormStructure";
import formCheckRule from "@/hooks/common/formCheckRule";
import tableShowRule from "@/hooks/common/tableShowRule";
import getBuildPosition from '@/hooks/report/getBuildPosition'
import axios from "axios";

export default {
  name: "BuildsPosition",
  setup(){
    // 表格数据
    let tableData = reactive({value:[]});
    const tableKey = ref(0);
    //获取表格数据
    getBuildPosition().then(data=>{
      tableData.value = data||[]
    }).catch(error=>{
      ElMessage.error(error)
    })

    //表头
    let tableHead = reactive({data: {}})
    //获取表单结构
    generateFormStructure('com.aier.bean.report.BuildsPosition').then(data=>{
      for (let i = 0; i < data.length; i++) {
        Object.keys(data[i]).forEach(key=>{
          tableHead.data[key] = data[i][key][1]
        })
      }
    }).catch(error=>{
      ElMessage.error(error.message)
    })
    // 搜索关键词
    const searchKeyword = ref('');
    // 状态筛选
    const searchStaffNameKeyword = ref('');
    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(5);


    const dynamicKeys = computed(() =>
        Object.keys(tableHead.data).filter(key =>
            !['fbaCode', 'sku'].includes(key)
        )
    );


    // 计算属性 - 筛选和分页后的数据
    const filteredData = computed(() => {
      let result = [...tableData.value];
      // 搜索过滤
      if (searchKeyword.value) {
        const keyword = searchKeyword.value;
        result = result.filter(item =>{
          return item.fbaCode.includes(keyword) ||
          item.sku.includes(keyword)

        });
      }

      // 员工姓名过滤
      if (searchStaffNameKeyword.value) {
        const keyword = searchStaffNameKeyword.value;
        result = result.filter(item => item.staffName.includes(keyword));
      }
      return result;
    });

    // 处理每页数量变化
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      currentPage.value = 1; // 重置到第一页
    };

    // 计算总条目数
    const totalItems = computed(() => filteredData.value.length);

    // 计算当前页显示的数据
    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      return filteredData.value.slice(start, start + pageSize.value);
    });

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1;
      tableKey.value++
    };

    // 处理分页变化
    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    const downloadExcel = async () => {
      try {
        const response = await axios.get('http://localhost:8888/report/download_build_position', {
          responseType: 'blob'
        });

        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '建仓表.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('下载失败:', error);
        ElMessage.error('建仓表下载失败');
      }
    }
    return {
      tableData,
      searchKeyword,
      downloadExcel,
      handleSizeChange,
      currentPageData,
      searchStaffNameKeyword,
      currentPage,
      tableKey,
      dynamicKeys,
      pageSize,
      tableHead,
      filteredData,
      totalItems,
      formCheckRule,
      tableShowRule,
      handleSearch,
      handlePageChange,
      Search
    };
  },
  components:[Search]
}
</script>

<style scoped>
.app-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 10px;
  height: 100%;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}
.header h1 {
  margin: 0;
  color: #409eff;
  font-weight: 600;
}
.upload-button{
  display: flex;
  gap: 10px;
}


.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.table-container {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.el-table .warning-row {
  background-color: #fef0f0;
}
.el-table .success-row {
  background-color: #f0f9eb;
}
</style>